package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.entity.Category;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.service.CategoryService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Category> selectCategory(Integer type) {
        return categoryMapper.selectCategory(type);
    }

    @Override
    public List<DishVO> selectDishByCategoryId(String categoryId) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        String cacheKey = "DISH_BY_CATEGORY_ID:" + categoryId;
        String vos = (String) valueOperations.get(cacheKey);
        if (StringUtils.hasText(vos)) {
            return JSON.parseArray(vos, DishVO.class);
        }
        List<DishVO> dishItemVOList = categoryMapper.selectDishByCategoryId(categoryId);
        dishItemVOList.forEach(dish -> {
            List<DishFlavor> dishFlavors = categoryMapper.selectFlavor(dish.getId());
            dish.setFlavors(dishFlavors);
        });
        valueOperations.set(cacheKey,JSON.toJSONString(dishItemVOList));
        return dishItemVOList;
    }
}
